package com.whfc.emp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.constant.RealNamePlatformConstant;
import com.whfc.emp.dao.AppEmpGroupMapper;
import com.whfc.emp.dao.AppEmpMapper;
import com.whfc.emp.dao.AppSyncRealNameConfigDao;
import com.whfc.emp.dto.AppEmpCorpDTO;
import com.whfc.emp.dto.AppGroupDTO;
import com.whfc.emp.dto.WxEmpGroupDTO;
import com.whfc.emp.entity.AppEmp;
import com.whfc.emp.entity.AppEmpGroup;
import com.whfc.emp.entity.AppSyncRealNameConfig;
import com.whfc.emp.param.AppEmpGroupAddParam;
import com.whfc.emp.param.AppEmpGroupEditParam;
import com.whfc.emp.realNamePlatform.jingZhou.JINGZHOUApi;
import com.whfc.emp.realNamePlatform.jingZhou.model.TeamDTO;
import com.whfc.emp.service.AppGroupService;
import com.whfc.fuum.dto.AppCorpDTO;
import com.whfc.fuum.service.AppCorpService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 人员班组服务
 *
 * @author hw
 * @version 1.0
 * @date 2020/12/29 10:02
 */
@DubboService(interfaceClass = AppGroupService.class, version = "1.0.0", timeout = 5000)
public class AppGroupServiceImpl implements AppGroupService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppEmpGroupMapper appEmpGroupMapper;

    @Autowired
    private AppEmpMapper appEmpMapper;

    @Autowired
    private AppSyncRealNameConfigDao appSyncRealNameConfigDao;

    @DubboReference(interfaceClass = AppCorpService.class, version = "1.0.0", timeout = 5000)
    private AppCorpService appCorpService;

    @Override
    public PageData<AppGroupDTO> list(Integer projectId, Integer pageNum, Integer pageSize, String keyword, Integer corpId) {
        logger.info("班组列表,projectId:{},pageNum:{},pageSize:{},keyword:{},corpId:{}", projectId, pageNum, pageSize, keyword, corpId);
        PageHelper.startPage(pageNum, pageSize);
        List<AppGroupDTO> list = appEmpGroupMapper.selectByProjectId(projectId, corpId, keyword);
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<AppGroupDTO> groupListByCorpId(Integer corpId) {
        logger.info("根据合作单位查找班组列表,corpId:{}", corpId);
        return appEmpGroupMapper.selectByCorpId(corpId);
    }

    @Override
    public List<AppGroupDTO> groupListByProjectId(Integer projectId) {
        logger.info("根据项目id查找班组,projectId:{}", projectId);
        return appEmpGroupMapper.selectByProjectId(projectId, null, null);
    }

    @Override
    public List<AppGroupDTO> list(Integer deptId, String keyword) throws BizException {
        return appEmpGroupMapper.selectByDeptId(deptId, keyword);
    }

    @Override
    public List<AppEmpCorpDTO> groupListByDeptId(Integer deptId, String keyword) {
        logger.info("根据组织机构查找班组列表,deptId:{}，keyword：{}", deptId, keyword);
        List<AppGroupDTO> list = appEmpGroupMapper.selectByDeptId(deptId, keyword);
        List<AppEmpCorpDTO> data = new ArrayList<>();
        list.forEach(appGroupDTO -> {
            AppEmpCorpDTO appEmpCorpDTO = new AppEmpCorpDTO();
            appEmpCorpDTO.setCorpId(appGroupDTO.getCorpId());
            appEmpCorpDTO.setCorpName(appGroupDTO.getCorpName());
            appEmpCorpDTO.setGroupList(new ArrayList<>());
            data.add(appEmpCorpDTO);
        });
        List<AppEmpCorpDTO> result = data.stream().distinct().collect(Collectors.toList());

        list.forEach(appGroupDTO -> {
            Integer corpId = appGroupDTO.getCorpId();
            result.forEach(appEmpCorpDTO -> {
                Integer corpId1 = appEmpCorpDTO.getCorpId();
                if (corpId.equals(corpId1)) {
                    appGroupDTO.setCorpId(null);
                    appGroupDTO.setCorpName(null);
                    appEmpCorpDTO.getGroupList().add(appGroupDTO);
                }
            });
        });
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(AppEmpGroupAddParam param) {
        logger.info("添加班组,param:{}", param);
        AppEmpGroup record = new AppEmpGroup();
        BeanUtils.copyProperties(param, record);
        Integer deptId = param.getDeptId();
        String groupCode = param.getGroupCode();
        if (StringUtils.isNotEmpty(groupCode)) {
            AppEmpGroup appEmpGroup = appEmpGroupMapper.selectGroupCodeAndDeptId(groupCode, deptId);
            if (appEmpGroup != null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "班组编码已存在");
            }
        }
        AppEmpGroup appEmpGroup = appEmpGroupMapper.selectByCorpIdAndName(param.getCorpId(), param.getGroupName());
        if (appEmpGroup != null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "当前合作单位下已存在该班组名称");
        }
        appEmpGroupMapper.insertSelective(record);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AppEmpGroupEditParam param) {
        logger.info("编辑班组,param:{}", param);
        Integer groupId = param.getGroupId();
        String groupCode = param.getGroupCode();
        AppEmpGroup appEmpGroup = appEmpGroupMapper.selectByPrimaryKey(groupId);
        if (appEmpGroup == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该班组不存在");
        }
        Integer deptId = appEmpGroup.getDeptId();
        if (StringUtils.isNotEmpty(groupCode)) {
            AppEmpGroup empGroup = appEmpGroupMapper.selectGroupCodeAndDeptId(groupCode, deptId);
            if (empGroup != null && !groupId.equals(empGroup.getId())) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "班组编码已存在");
            }
        }
        String newGroupName = param.getGroupName();
        if (StringUtils.isNotEmpty(newGroupName) && !newGroupName.equals(appEmpGroup.getGroupName())) {
            appEmpMapper.updateGroupNameByGroupId(newGroupName, groupId);
        }

        BeanUtils.copyProperties(param, appEmpGroup);
        appEmpGroupMapper.updateByPrimaryKey(appEmpGroup);
    }

    @Override
    public void del(Integer groupId) {
        logger.info("删除班组,groupId:{}", groupId);
        List<AppEmp> list = appEmpMapper.selectByGroupId(groupId);
        if (list.size() > 0) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该班组下有人员,不能删除。");
        }
        AppEmpGroup appEmpGroup = appEmpGroupMapper.selectByPrimaryKey(groupId);
        // 异步删除
        CompletableFuture.runAsync(()->{
            AppSyncRealNameConfig appSyncRealNameConfig = appSyncRealNameConfigDao.selectByDeptIdAndPlatform(appEmpGroup.getDeptId(), RealNamePlatformConstant.JING_ZHOU);
            if (appSyncRealNameConfig != null) {
                JINGZHOUApi.syncDelTeam(appEmpGroup, appSyncRealNameConfig);
            }
        });
        appEmpGroupMapper.deleteLogicById(groupId);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncGroup(AppEmpGroupEditParam param) {
        AppEmpGroup appEmpGroup = appEmpGroupMapper.selectByPrimaryKey(param.getGroupId());
        AppSyncRealNameConfig appSyncRealNameConfig = appSyncRealNameConfigDao.selectByDeptIdAndPlatform(appEmpGroup.getDeptId(), RealNamePlatformConstant.JING_ZHOU);
        if (appSyncRealNameConfig != null) {
            if (0==appEmpGroup.getSyncState()) {
                // 同步荆州实名制系统新增
                JSONObject jsonObject = JINGZHOUApi.syncTeam(appEmpGroup, appSyncRealNameConfig, JINGZHOUApi.TEAM_UPLOAD);
                if (0 == jsonObject.getInteger("code")) {
                    appEmpGroup.setSyncState(1);
                    appEmpGroupMapper.updateByPrimaryKey(appEmpGroup);
                }
            }else {
                // 同步荆州实名制系统修改
                JINGZHOUApi.syncTeam(appEmpGroup, appSyncRealNameConfig, JINGZHOUApi.TEAM_UPDATE);
            }
        }
    }

    @Override
    public void syncCropName(Integer deptId) {
        List<AppGroupDTO> appGroupDTOS = appEmpGroupMapper.selectByDeptId(deptId, null);
        if (CollectionUtils.isEmpty(appGroupDTOS)) {
            return;
        }
        List<Integer> corpIds = appGroupDTOS.stream().map(AppGroupDTO::getCorpId).distinct().collect(Collectors.toList());
        List<AppCorpDTO> list = appCorpService.list(corpIds);
        for (AppCorpDTO appCorpDTO : list) {
            appEmpGroupMapper.updateCorpNameByCorpId(appCorpDTO.getCorpId(),appCorpDTO.getCorpName(),appCorpDTO.getCorpCode());
        }
    }
}
